package middle

import (
	"github.com/gin-gonic/gin"
	"github.com/vueadmin/app/admin/internal/svc"
	"github.com/vueadmin/pkg/cache"
	"github.com/vueadmin/utils/conv"
	"github.com/vueadmin/utils/response"
	"time"
)

type BeforActionMiddleware struct {
	svcCtx *svc.ServiceContext
}

func NewBeforActionMiddleware(svcCtx *svc.ServiceContext) *BeforActionMiddleware {
	return &BeforActionMiddleware{
		svcCtx: svcCtx,
	}
}

// 获取不用验证权限的方法
func (p BeforActionMiddleware) GetNotAuthUri() []string {
	return []string{
		"/admin/Login/verify",
		"/admin/Base/getSiteInfo",
		"/admin/Index/main",
		"/admin/Base/getShenshiqu",
		"/admin/Upload/upload",
		"/admin/Base/fileList",
		"/admin/Upload/createFile",
		"/admin/Base/clearCache",
		"/admin/Base/getRoleMenus",
	}
}

// 获取系统配置信息中间件
func (p BeforActionMiddleware) Handle() gin.HandlerFunc {
	return func(c *gin.Context) {
		data, _ := cache.New(p.svcCtx.Redis).Remember(c.Request.Host+"/base_config", 30*time.Second, func() (string, error) {
			return p.getInfo()
		})
		for k, v := range conv.StringToObject(data) {
			c.Set(k, v)
		}
		uri := c.Request.URL.Path
		if conv.IsValueInList(uri, p.GetNotAuthUri()) {
			return
		}
		access := conv.Slice(c.Value("access"))
		if conv.Int(c.Value("role_id")) != 1 && !conv.IsValueInList(uri, access) {
			response.Fail(c, "没有权限访问")
			c.Abort()
			return
		}
		c.Next()
	}
}

type adminBaseconfig struct {
	Name string `json:"name"`
	Data string `json:"data"`
}

// 获取配置信息
func (p BeforActionMiddleware) getInfo() (string, error) {
	var entity []*adminBaseconfig
	if err := p.svcCtx.Db.Table("cd_base_config").Find(&entity).Error; err != nil {
		return "", err
	}
	config := make(map[string]interface{})
	for _, val := range entity {
		config[val.Name] = val.Data
	}
	config["keyword"] = conv.StringToSlice(conv.String(config["keyword"]), ",")

	return conv.String(config), nil
}
